$(function() {
	var $editForm = $('#editForm');
	var $btnSave = $('#btnSave');
	var $btnReset = $('#btnReset');
	var $timeZoneList = $('#timeZoneList');
	
	var formData;
	var timeZoneID;
	
	initGeneralData();
	initListeners();
	initValidators();
	
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$editForm.validate({
			rules: {
				mineName: { required: true, minlength: 2, maxlength: 20 },
			}
		});
	}
	
	function initListeners() {
		$btnReset.on('click', function() {
			initFormData(formData);
		});
		
		$btnSave.on('click', function() {
			saveGeneralData();
		});
	}
	
	function saveGeneralData() {
		var valid = $editForm.validate().form();
		if (!valid) {
			return;
		}
		var fdata = $editForm.serializeObject();
		fdata.timeZoneID = $timeZoneList.val();
		var data = JSON.stringify(fdata);
		doSave(data);
	}
	
	function doSave(data) {
		$.ajax({
			url: 'generals',
			type: 'POST',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success('系统常规选项设置成功！', '保存成功');
					initGeneralData();
				} else {
					toastr.error(result.message, '保存失败');
				}
				window.parent.location.reload();
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}
	
	function initGeneralData() {
		$.ajax({
			url: 'generals',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					initFormData(result.data);
				} else {
					toastr.error(result.message, '失败');
				}
				initTimeZoneList();
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}
	
	function initFormData(data) {
		fromData = data;
		$('#mineName').val(data.mineName);
		$('#mineSerial').val(data.mineSerial);
		timeZoneID = data.timeZoneID;
	}
	
	function initTimeZoneList() {
		$timeZoneList.chosen({allow_single_deselect: true, width:'100%'});
		$.ajax({
			url: 'timezones',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					if (result.data) {
						$timeZoneList.empty();
						$timeZoneList.append($('<option></option>').val('').html(''));
						for (var i=0; i<result.data.length; i++) {
							var tz = result.data[i];
							$timeZoneList.append($('<option></option>').val(tz.id).html(tz.display));
						}
						$timeZoneList.val(timeZoneID);
						$timeZoneList.chosen('destroy').chosen({allow_single_deselect: true, width:'100%'});
					}
				} else {
					toastr.error('时区列表获取失败！', '失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '时区列表获取异常');
			}
		});
	}
});